package com.gs.common.shiro;

/**
 * @title: 孙杨申
 * @date 2021/12/4 20:44
 */

import cn.hutool.core.util.ObjectUtil;
import com.gs.common.util.JWTUtil;
import com.gs.disk.dto.admin.RoleDto;
import com.gs.disk.service.admin.UserService;

import com.gs.entity.UserEntity;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Set;

public class CustomJWTRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Value("${spring.profiles.active}")
    public String profile;
    /**
     * 必须重写此方法，不然会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * @MethodName doGetAuthorizationInfo
     * @Description 权限配置类
     * @Param [principalCollection]
     * @Return AuthorizationInfo
     * @Author WangShiLin
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
//        String username = JWTUtil.getUsername(principalCollection.toString());
        String username = ((UserEntity) principalCollection.getPrimaryPrincipal()).getName();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获得该用户角色
        Set<RoleDto> role = userService.getRole(username);
        //每个角色拥有默认的权限
        Set<String> rolePermission = userService.getUserRolePermission(username);

        //设置该用户拥有的角色和权限
        role.forEach(dto -> info.addRole(dto.getRoleName()));
        info.setStringPermissions(rolePermission);
        return info;
    }

    /**
     * @MethodName doGetAuthenticationInfo
     * @Description 认证配置类
     * @Param [authenticationToken]
     * @Return AuthenticationInfo
     * @Author WangShiLin
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String username = JWTUtil.getUsername(token);

        // 万能token 用于测试
        String allPowerToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiMSIsImV4cCI6MTY2OTIwNzE3N30.DTLWxhendmKY7qM9L48wlPRhLpVrbxLnuShbZv2epGM";

        if("dev".equals(profile) && allPowerToken.equals(token)) {
            UserEntity userEntity = userService.getById(1L);
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userEntity, token, getName());
            return simpleAuthenticationInfo;
        } else if(username == null || !JWTUtil.verify(token, username)) {
            throw new AuthenticationException("token认证失败！");
        }
        UserEntity user = userService.getByUserName(username);
        String password = user.getEncodePassword();
        if (password == null) {
            throw new AuthenticationException("该用户不存在！");
        }
        // 这个得加字段
//        int ban = userService.getByUserName(username).get.checkUserBanStatus(username);
//        if (ban == 1) {
//            throw new AuthenticationException("该用户已被封号！");
//        }

        if (ObjectUtil.isEmpty(authenticationToken.getPrincipal())) {
            return null;
        }
        //获取用户信息
        String name = authenticationToken.getPrincipal().toString();
        if (user == null) {
            //这里返回后会报出对应异常
            return null;
        } else {
            //这里验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, token, getName());
            return simpleAuthenticationInfo;
        }
    }
}
